<template>
  <div class='container' :class='{"van-overflow-hidden": showWrapper}'>
    <div class='header'>
      <van-search
        v-model.trim='inputValue'
        show-action
        :placeholder='placeholder'
        @search='onSearch'
        @cancel='onCancel'
        @focus='onFocus'
        @update:model-value='input'
      >
      </van-search>
    </div>
    <div class='relevant' v-show='showRelevant'>
      <ul>
        <li v-for='(item, index) in keywords' :key='index' @click='onSearch(item)'>
          <span>{{ item }}</span>
          <van-icon name='arrow' />
        </li>
      </ul>
    </div>
    <div class='nav nav_history' v-show='showHistory'>
      <div class='nav_title'>历史记录
        <van-icon name='delete-o' class='delIcon' @click='clearHis' />
      </div>
      <div class='nav_list'>
        <div class='nav_item' @click='onSearch(item)'
             v-for='(item, index) in history'
             :key='index'>
          <van-tag
            size='medium'
            color='#999'
            text-color='black'
            plain
            type='primary'
          >
            {{ item }}
          </van-tag>
        </div>
      </div>
    </div>
    <div class='nav' v-show='showHot'>
      <div class='nav_title'>热门搜索</div>
      <div class='nav_list'>
        <div class='nav_item' @click='onSearch(item.keyword)'
             v-for='(item, index) in hotInfo'
             :key='index'>
          <van-tag
            size='medium'
            :color='index === 0 ? "#dd1a21" : "#999"'
            :text-color='index === 0 ? "#dd1a21" : "#999"'
            plain
            type='primary'
          >
            {{ item.keyword }}
          </van-tag>
        </div>
      </div>
    </div>
    <div class='good' v-show='showGood'>
      <div class='goodNav'>
        <van-tabs v-model:active='sortType' @click-tab='onClickTab'>
          <van-tab title='综合'></van-tab>
          <van-tab title='价格'></van-tab>
          <van-tab title='分类'></van-tab>
        </van-tabs>
        <div class='wrapper' v-show='showWrapper'>
          <form class='sortForm' @submit.prevent v-show='isShowSort'>
            <div class='formItem'>
              <span>筛选</span>
              <input class='smallBtn' type='number' v-model='sortParams.minPrice' placeholder='最低价' />
              <div class='line'></div>
              <input class='smallBtn' type='number' v-model='sortParams.maxPrice' placeholder='最高价' />
            </div>
            <div class='formItem'>
              <span>排序</span>
              <button class='smallBtn'
                      :class='{ active: !sortParams.isDesc}'
                      @click='sortParams.isDesc = false'>从低到高
              </button>
              <button class='smallBtn'
                      :class='{ active: sortParams.isDesc}'
                      @click='sortParams.isDesc = true'>从高到低
              </button>
            </div>
          </form>
          <div class='confirm' v-show='isShowSort'>
            <button class='bitBtn' style='border-right: 1px solid #d9d9d9' @click='cancelSort'>取消</button>
            <button class='bitBtn' style='color: #dd1a21' @click='confirmSort'>确定</button>
          </div>
          <div class='classify' v-show='!isShowSort'>
            <div
              class='classify_tag'
              v-for='item in goodList.categoryL1List'
              :key='item.id'
              @click='category(item.id)'
            >
              {{ item.name }}
            </div>
          </div>
          <div class='modal' @click='showWrapper = false'></div>
        </div>
      </div>
      <MyGoodList :good-list='goodList.directlyList' />
    </div>
  </div>
</template>

<script setup lang='ts'>
import { computed, onMounted, ref } from 'vue'
import { reqGoodList, reqInputKeyword, reqTagInfo } from '@/api/search.ts'
import type { DefKeywordVOItem, HotKeywordVOItem } from '@/types/search.d.ts'
import type { GoodList, ReqGoodListParams } from '@/types/search.d.ts'
import type { SortParams } from '@/types/search.d.ts'
import type { TabsInstance } from 'vant'
import { debounce } from 'lodash';

// 双向绑定的搜索框的值
const inputValue = ref('')
// 默认关键字列表
const placeholders = ref<DefKeywordVOItem[]>([])
// 随机默认关键字
const placeholder = computed(() => {
  const index = Math.floor(Math.random() * (placeholders.value.length))
  return placeholders.value.length ? placeholders.value[index].keyword : '请输入关键词'
})
// 历史记录
const history = ref<string[]>([])
history.value = JSON.parse(window.localStorage.getItem('history') as string) || []
// 搜索关联词
const keywords = ref<string[]>([])
// 热门关键字
const hotInfo = ref<HotKeywordVOItem[]>([])
// 商品数据
const goodList = ref<GoodList>({
  hasMore: true,
  directlyList: [],
  categoryL1List: []
})
// 综合 排序 分类 样式控制
const sortType = ref(0)
// 控制模态框的展示内容
const isShowSort = ref<boolean>(false)
// 排序参数
const sortParams = ref<SortParams>({
  isDesc: false,
  minPrice: 0,
  maxPrice: 0
})

// 控制商品列表的展示与隐藏
const showGood = ref<boolean>(false)
// 控制热门关键字的展示与隐藏
const showHot = ref<boolean>(!!hotInfo.value.length)
// 控制关联词的显示与隐藏
const showRelevant = ref<boolean>(false)
// 控制历史记录的显示与隐藏
const showHistory = ref<boolean>(!!history.value.length)
// 控制筛选和分类和模态框的展示与隐藏
const showWrapper = ref<boolean>(false)
// 搜索框聚焦
const onFocus = () => {
  // 修改展示与隐藏布局
  showGood.value = false
  showHot.value = !!keywords.value.length ? false : !!hotInfo.value.length
  showRelevant.value = !!keywords.value.length
  showHistory.value = !!keywords.value.length ? false : !!history.value.length
}

// 排序界面的取消按钮
const cancelSort = () => {
  // todo
  showWrapper.value = false
}
// 排序界面的确定按钮
const confirmSort = () => {
  console.log(sortParams.value)
  getGoodList(inputValue.value, sortParams.value)

  showWrapper.value = false
}

// 清除历史记录
const clearHis = () => {
  history.value = []
  showHistory.value = false
  window.localStorage.removeItem('history')
}

// 执行搜索的方法
const onSearch = (value: string) => {
  inputValue.value = value
  if (value) {
    // 修改展示与隐藏布局
    showGood.value = true
    showHot.value = false
    showRelevant.value = false
    showHistory.value = false
    // 向历史记录中添加此次关键词
    history.value.push(value)
    const newHistory = [...new Set(history.value)]
    // 将历史记录同步更新到本地
    window.localStorage.setItem('history', JSON.stringify(newHistory))
    // 准备请求参数
    getGoodList(value)
  }
}

const getGoodList = async (value: string, sortParams?: SortParams, cateId?: number) => {
  const params: ReqGoodListParams = {
    csrf_token: '24afadba8ecaf8db86513c0b6a260b86',
    __timestamp: +new Date(),
    keyword: value,
    sortType: 0,
    descSorted: sortParams?.isDesc || false,
    categoryId: cateId || 0,
    matchType: 0,
    floorPrice: sortParams?.minPrice || -1,
    upperPrice: sortParams?.maxPrice || -1,
    size: 40,
    itemId: 0,
    stillSearch: false,
    searchWordSource: 1,
    needPopWindow: true,
    _stat_search: 'userhand'
  }
  const res = await reqGoodList(params)
  if (res.code === '200') {
    goodList.value = res.data
  }
}

// 监听输入框变化的方法
const input = debounce(async (value: string) => {
  if (value === '') return
  // 发送请求获取关联词
  const res = await reqInputKeyword(value)
  if (res.code === '200') {
    // 更新状态，重新渲染视图
    keywords.value = res.data
  }
  // 修改展示与隐藏布局
  showGood.value = false
  showHot.value = false
  showRelevant.value = !!keywords.value.length
  showHistory.value = false
}, 300)

// 点输入框右侧取消的方法
const onCancel = () => {
  inputValue.value = ''
  getGoodList(placeholder.value)
  // 修改展示与隐藏布局
  showGood.value = true
  showHot.value = false
  showRelevant.value = false
  showHistory.value = false
}

const getTagInfo = async () => {
  const res = await reqTagInfo()
  if (res.code === '200') {
    hotInfo.value = res.data.hotKeywordVOList
    placeholders.value = res.data.defaultKeywords
    showHot.value = !!hotInfo.value.length
  }
}

const onClickTab = ({ title }: TabsInstance) => {
  if (title === '价格') {
    showWrapper.value = true
    isShowSort.value = true
  } else if (title === '分类') {
    showWrapper.value = true
    isShowSort.value = false
  } else if (title === '综合') {
    showWrapper.value = false
    isShowSort.value = false
  }
}

const category = (id: number) => {
  getGoodList(inputValue.value, sortParams.value, id)
  showWrapper.value = false
}

onMounted(() => {
  // 获取默认关键字和热门关键字
  getTagInfo()
})

</script>

<script lang='ts'>
export default {
  name: 'MySearch'
}
</script>

<style scoped lang='less'>
.container {
  background-color: #eee;
  box-sizing: border-box;
  height: 100%;
  outline: none;
}

.header {
  width: 100%;
  height: 50px;
  background-color: #fff;
  margin-top: 5px;
}

.relevant {
  ul {
    background-color: #fff;
    padding: 5px 5px 0 10px;

    li {
      height: 45px;
      line-height: 45px;
      font-size: 14px;
      border-bottom: 1px solid #eee;
      display: flex;
      justify-content: space-between;
    }

    :deep(.van-icon-arrow) {
      line-height: 52px;
    }
  }
}

.nav_item {
  margin: 0 16px 16px 0;
}

.nav_history {
  overflow: hidden;
}

.delIcon {
  line-height: 50px;
  color: black;
}

.nav {
  margin: 0 0 10px;
  padding: 0 15px 15px;
  background-color: #fff;
  height: 130px;
  display: flex;
  flex-direction: column;
  align-content: space-between;


  .nav_title {
    height: 50px;
    line-height: 50px;
    color: #999;
    font-size: 15px;
    display: flex;
    justify-content: space-between;
  }

  .nav_list {
    height: 80px;
    display: flex;
    flex-wrap: wrap;
    justify-content: flex-start;
  }
}

.wrapper {
  position: absolute;
  background-color: #fff;
  width: 100%;
  z-index: 20;
  height: 110px;

  .classify {
    border-top: 1px solid #d9d9d9;
    background-color: #fff;
    font-size: 14px;
    height: 110px;
    width: 375px;
    color: #333;
    padding: 0.4rem 0.3rem 0;
    display: flex;
    align-content: space-evenly;
    flex-wrap: wrap;
    overflow: hidden;

    .classify_tag{
      height: 28px;
      margin-right: 0.4rem;
      margin-bottom: 0.4rem;
      padding: 0 0.18rem;
      line-height: 28px;
      letter-spacing: 0;
      border: 0.01rem solid #7f7f7f;
      border-radius: 0.04rem;
      color: #333;
      font-size: .28rem;
      text-align: center;
    }
  }

  .modal{
    position: relative;
    z-index: 9999;
    left: 0;
    bottom: 0;
    width: 100%;
    height: 450px;
    overflow: auto;
    background-color: rgba(0, 0, 0, 0.6);
  }
}


.sortForm {
  background-color: #fff;
  font-size: 14px;
  height: 110px;
  width: 375px;
  color: #333;
  padding: 0.4rem 0.3rem 0;
  display: flex;
  align-content: space-evenly;
  flex-wrap: wrap;

  .formItem {
    margin-bottom: 0.4rem;
    display: flex;
    align-items: center;

    span {
      margin-right: 20px;
    }

    .line {
      display: inline-block;
      margin: 0 0.22rem;
      width: 0.22rem;
      height: 0.02rem;
      background: #7f7f7f;
    }

    .smallBtn {
      margin-right: 0.24rem;
      width: 104px;
      height: 28px;
      text-align: center;
      background-color: #fff;
      border: 1px solid #7f7f7f;
      border-radius: 0.04rem;
      font-size: .28rem;
      line-height: .56rem;
      color: #333;
    }
  }
}

.confirm {
  .bitBtn {
    height: 52px;
    width: 50%;
    text-align: center;
    font-size: .28rem;
    color: #333;
    line-height: 1.04rem;
    border: none;
    border-top: 1px solid #d9d9d9;
    background: #fff;
  }
}

.active {
  color: #dd1a21 !important;
  border: 1px solid #dd1a21 !important;
}

</style>
